import axios from "axios";
import { Notify } from "react-vant";
import { store } from "../app/store";
import { quitLogin } from "../app/modules/user";
export const request = axios.create({});

// 请求
request.interceptors.request.use((config) => {
  const state = store.getState();
  config.headers.userId = state.user.userInfo.userId;
  config.headers.sessionId = state.user.userInfo.sessionId;
  return config;
});

// 响应
request.interceptors.response.use(
  (response) => {
    // 前后端约定 状态
    // 0000	请求接口成功
    const { status, message } = response.data;
    switch (status) {
      case "9999":
        store.dispatch(quitLogin());
        console.log("登录状态失效，请重新登录");
        break;
      case "9001":
        console.log("服务端错误");
        break;
      case "8001":
        Notify.show({ type: "danger", message: message || "用户业务错误" });
        break;
      case "8002":
        console.log("医生业务错误");
        break;
      case "8003":
        console.log("公共业务错误");
        break;
    }

    return response;
  },
  (error) => {
    const { status } = error.response;
    if(status === 400) {
      store.dispatch(quitLogin());
    }
    console.log("error", error);
    return Promise.reject(error);
  }
);

// 抛出 post
export function httpPost(url: string, data = {}) {
  return request({
    url: "/api" + url,
    data,
    method: "post",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
  });
}

// 抛出 put
export function httpPut(url: string, data = {}) {
  return request({
    url: "/api" + url,
    data,
    method: "put",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
  });
}

export function httpPostJSON(url: string, data = {}) {
  return request({
    url: "/api" + url,
    data,
    method: "post",
    headers: {
      "Content-Type": " application/json",
    },
  });
}

// 抛出 get
export function httpGet(url: string, params = {}) {
  return request({
    url: "/api" + url,
    params: params,
    method: "get",
  });
}
